const ws = require('ws');

((ws) => {

        const server = new ws.Server({
                port: 5555
        });

        const init = () => {
                bindEvent()

                setInterval(() => {
                        server.clients.forEach(c => {

                                c.send(JSON.stringify(createData()));

                        })
                }, 1000 + Math.random() * 1000)
        }

        function bindEvent(event) {
                server.on('open', handleOpen);
                server.on('close', handleClose);
                server.on('error', handleError);
                server.on('connection', handleConnection);
        }

        function handleOpen() {
                console.log('WebSocket open');
        }

        function handleClose() {
                console.log('WebSocket close');
        }

        function handleError() {
                console.log('WebSocket error');
        }

        function handleConnection(ws) {
                console.log('WebSocket connection');

        }
        init()
})(ws)

const licenceList = ['长相思兮长相忆', '短相思兮无穷极', '相思相见知何日', '此时此夜难为情', '何处春江无月明', '滟滟随波千万里', '金风玉露一相逢', '便胜却人间无数']
const colorList = ['蓝', '绿', '黄', '蓝', '绿', '蓝', '绿']
const typeList = ['car1', 'car2', 'car3', 'car1', 'car1', 'car1', 'car2']

function createData() {
        const beginTimeStamp = new Date().getTime()
        const middleTimeStamp = beginTimeStamp + 5000 + Math.random() * 2000
        const endTimeStamp = middleTimeStamp + 5000 + Math.random() * 2000
        const licence = licenceList[parseInt(Math.random() * 8)]
        const color = colorList[parseInt(Math.random() * 7)]
        const type = typeList[parseInt(Math.random() * 7)]
        const line = parseInt(Math.random() * 2)

        const res = {
                beginTimeStamp: beginTimeStamp,
                middleTimeStamp: middleTimeStamp,
                endTimeStamp: endTimeStamp,
                licence: licence,
                color: color,
                type: type,
                line: line
        }

        return res
}